package com.shfl.task.logic.api;

import com.github.pagehelper.PageInfo;
import com.shfl.task.common.ApiResultHelper;
import com.shfl.task.common.ApiResultPagingHelper;
import com.shfl.task.common.RequestHelper;
import com.shfl.task.common.SystemConstant;
import com.shfl.task.logic.constants.CommonConstants;
import com.shfl.task.logic.model.request.AddTaskJobRequest;
import com.shfl.task.logic.model.request.CloseTaskJobRequest;
import com.shfl.task.logic.model.request.OpenTaskJobRequest;
import com.shfl.task.logic.model.response.TaskJobResponse;
import com.shfl.task.logic.service.TaskJobService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/task/job")
public class TaskJobController {

    @Autowired
    private TaskJobService taskJobService;

    @GetMapping(value = "/page/list")
    public ApiResultPagingHelper<TaskJobResponse, Void> page(
            RequestHelper requestHelper
    ) {
        requestHelper.apply();
        Map<String, Object> objectMap = requestHelper.getKeyMap();
        PageInfo<TaskJobResponse> pageInfo = taskJobService.findPage(requestHelper.getPageable(), objectMap);
        if (pageInfo.getTotal() > 0) {
            pageInfo.getList().forEach(item -> {
                item.setJobStatusValue(CommonConstants.JobStatus.getName(item.getJobStatus()));
                item.setJobTypeValue(CommonConstants.JobType.getName(item.getJobType()));
            });
        }
        return new ApiResultPagingHelper<>(SystemConstant.RE_SUCCESS_CODE,
                pageInfo.getTotal(), pageInfo.getPageSize(), pageInfo.getPageNum(),
                pageInfo.getList());
    }


    @PostMapping("/add")
    public ApiResultHelper add(
            @RequestBody @Validated AddTaskJobRequest request) throws Exception {
        taskJobService.add(request);
        return new ApiResultHelper(SystemConstant.RE_SUCCESS_CODE);
    }

    @PostMapping("/edit")
    public ApiResultHelper edit(
            @RequestBody @Validated AddTaskJobRequest request) throws Exception {
        taskJobService.edit(request);
        return new ApiResultHelper(SystemConstant.RE_SUCCESS_CODE);
    }

    @PostMapping("/close")
    public ApiResultHelper close(
            @RequestBody @Validated CloseTaskJobRequest request) throws Exception {
        taskJobService.close(request);
        return new ApiResultHelper(SystemConstant.RE_SUCCESS_CODE);
    }

    @PostMapping("/open")
    public ApiResultHelper open(
            @RequestBody @Validated OpenTaskJobRequest request) throws Exception {
        taskJobService.open(request);
        return new ApiResultHelper(SystemConstant.RE_SUCCESS_CODE);
    }
}
